package handle

import (
	"server/game/model"

	"github.com/hwcer/cosgo/registry"
	"github.com/hwcer/cosmo"
	"github.com/hwcer/cosmo/update"
	"github.com/hwcer/yyds/context"
)

func init() {
	Register(&Mail{})
}

/*
mail 邮件相关
*/

type Mail struct {
}

func (this *Mail) Caller(node *registry.Node, handle *context.Context) interface{} {
	f := node.Method().(func(*Mail, *context.Context) interface{})
	return f(this, handle)
}

// Getter 获取邮件
func (this *Mail) Getter(c *context.Context) interface{} {
	paging := &cosmo.Paging{}
	if err := c.Bind(paging); err != nil {
		return err
	}
	paging.Init(100)
	paging.Rows = []*model.Mail{}
	uid := c.Uid()
	tx := db.Omit("uid")
	tx = tx.Where("uid = ?", uid)
	tx = tx.Where("status != ?", model.MailStatusDelete)
	tx = tx.Where("expire > ?", c.Unix())

	if tx = tx.Page(paging); tx.Error != nil {
		return tx.Error
	}
	return paging
}

// Read 设置已读
// param id 邮件id,多个以“,”分割,为空为一间领取
func (this *Mail) Read(c *context.Context) interface{} {
	var id []string
	if err := c.Bind(&id); err != nil {
		return err
	}
	tx := db.Model(&model.Mail{}).Where("uid = ?", c.Uid()).Order("update", -1)
	tx = tx.Where("status = ?", model.MailStatusNone)
	if len(id) > 0 {
		tx = tx.Where(id)
	}
	if tx = tx.Set("status", model.MailStatusRead); tx.Error != nil {
		return tx.Error
	}

	return true
}

// Remove 删除邮件
// param id 邮件id,多个以“,”分割,为空为一键清理
func (this *Mail) Remove(p *context.Context) interface{} {
	var id []string
	if err := p.Bind(&id); err != nil {
		return err
	}
	tx := db.Model(&model.Mail{}).Where("uid = ?", p.Uid()).Order("update", -1)
	tx = tx.Where("submit = ?", 0)
	if len(id) > 0 {
		tx = tx.Where(id)
	} else {
		tx = tx.Where("status = ?", model.MailStatusRead)
	}
	if tx = tx.Set("status", model.MailStatusDelete); tx.Error != nil {
		return tx.Error
	}
	return true
}

// Submit 领取附件
// param id 邮件id,多个以“,”分割,为空为一键领取 前20条
func (this *Mail) Submit(c *context.Context) interface{} {
	var id []string
	if err := c.Bind(&id); err != nil {
		return err
	}
	tx := db.Select("status", "attr")
	tx = tx.Limit(20).Order("update", -1)
	tx = tx.Where("uid = ?", c.Uid())
	tx = tx.Where("submit > ?", 0)
	tx = tx.Where("expire > ?", c.Unix())
	tx = tx.Where("status != ?", model.MailStatusDelete)
	if len(id) > 0 {
		tx = tx.Where(id)
	}
	var ret []*model.Mail
	tx = tx.Find(&ret)
	if tx.Error != nil {
		return tx.Error
	} else if tx.RowsAffected == 0 {
		return 0
	}
	var ids []string
	items := map[int32]int32{}
	for _, d := range ret {
		ids = append(ids, d.OID)
		for _, attr := range d.Attr {
			if attr.K > 0 && attr.V > 0 {
				items[attr.K] += attr.V
			}
		}
	}
	for k, v := range items {
		c.Player.Add(k, v)
	}

	var m *model.Mail
	upsert := update.Update{}
	upsert.Set("submit", 0)
	upsert.Set("status", model.MailStatusRead)
	tx = db.Model(m).Multiple().Update(upsert, ids)
	if tx.Error != nil {
		return tx.Error
	} else {
		return ids
	}
}
